
#import <Foundation/Foundation.h>
#import "VideoRecordViewController.h"
#import <TXLiteAVSDK_Enterprise/TXUGCRecord.h>
//#import "TCVideoPublishController.h"
#import "VideoPreviewViewController.h"
#import <AVFoundation/AVFoundation.h>

#import "UIView+Additions.h"
#import "BeautySettingPanel.h"
#import "VideoEditViewController.h"
#import "QBImagePickerController.h"
#import "VideoLoadingController.h"
#import "VideoEditViewController.h"
#import <TXLiteAVSDK_Enterprise/TXVideoEditer.h>
//#import "WaitReciveViewController.h"
#import "XLAnchorCommitInforVC.h"
#import "XLVideoSetController.h"


#define BUTTON_RECORD_SIZE          65
#define BUTTON_CONTROL_SIZE         40
#define MAX_RECORD_TIME             60
#define MIN_RECORD_TIME             10


@interface VideoRecordViewController()<
TXUGCRecordListener,
BeautySettingPanelDelegate,
TXVideoCustomProcessDelegate,
QBImagePickerControllerDelegate
>
{
    BOOL                            _cameraFront;
    BOOL                            _lampOpened;
    BOOL                            _bottomViewShow;
    
    int                             _beautyDepth;
    int                             _whitenDepth;
    
    BOOL                            _cameraPreviewing;
    BOOL                            _videoRecording;
    UIView *                        _videoRecordView;
    UIButton *                      _btnStartRecord;
    UIButton *                      _btnCamera;
    UIButton *                      _btnBeauty;
    UIButton *                      _btnLamp;
    UIButton *                      _btnDone;
    UIButton *                      _btnLive;
    UIButton *                      _nextStepBtn;
    BOOL                            _isPaused;
    BOOL                            _isLocalVideo;
    UIProgressView *                _progressView;
    UILabel *                       _recordTimeLabel;
    int                             _currentRecordTime;

    BeautySettingPanel*             _vBeauty;
    
    BOOL                            _navigationBarHidden;
    BOOL                            _statusBarHidden;
    BOOL                            _appForeground;
    
    UIView*                         _tmplBar;
    
    UIDeviceOrientation             _deviceOrientation;
    
    
    AVAudioPlayer*                  _player;
    NSTimer*                        _timer;
    NSArray*                        _assetsAry;
    AVAsset*                        _videoAsset;
    UIView *                        _minimumView;
}
@end


@implementation VideoRecordViewController

-(instancetype)init
{
    self = [super init];
    if (self)
    {
        //self.currentPageId = @"video_record";
        _cameraFront = YES;
        _lampOpened = NO;
        _bottomViewShow = NO;
        
        _beautyDepth = 6.3;
        _whitenDepth = 2.7;
        
        _cameraPreviewing = NO;
        _videoRecording = NO;

        _currentRecordTime = 0;
        
        [TXUGCRecord shareInstance].recordDelegate = self;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidEnterBackGround:) name:UIApplicationDidEnterBackgroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(onAudioSessionEvent:)
                                                     name:AVAudioSessionInterruptionNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChanged:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
        _appForeground = YES;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    if (_videoRecording) {
        [self stopVideoRecord];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
   
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    self.fd_interactivePopDisabled = YES;
    [self initUI];
    [self initBeautyUI];
    self.view.backgroundColor = UIColor.whiteColor;
    _isLocalVideo = NO;
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    _navigationBarHidden = self.navigationController.navigationBar.hidden;
    self.navigationController.navigationBar.hidden = NO;
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
        [self startCameraPreview];

//    _statusBarHidden = [UIApplication sharedApplication].statusBarHidden;
//    [self.navigationController setNavigationBarHidden:YES];
//    self.navigationController.navigationBar.hidden = NO;
//    [[UIApplication sharedApplication]setStatusBarHidden:YES];


}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
//    [BMHStatisticsTool beginLogPageView:@"短视频录制页"];
//    [[[BMHAPIManager sharedStatManager] gatherCurrentPageId:self.currentPageId previousPageId:self.previousPageId videoId:nil] subscribeNext:^(id x) {
//        NSLog(@"%@", x);
//    } error:^(NSError *error) {
//        NSLog(@"%@", error);
//    }];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    //[BMHStatisticsTool endLogPageView:@"短视频录制页"];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBar.hidden = _navigationBarHidden;
    
    [self stopCameraPreview];
}

-(void)viewDidUnload
{
    [super viewDidUnload];
}

-(void)onAudioSessionEvent:(NSNotification*)notification
{
    NSDictionary *info = notification.userInfo;
    AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    if (type == AVAudioSessionInterruptionTypeBegan) {
        // 在10.3及以上的系统上，分享跳其它app后再回来会收到AVAudioSessionInterruptionWasSuspendedKey的通知，不处理这个事件。
        if ([info objectForKey:@"AVAudioSessionInterruptionWasSuspendedKey"]) {
          
            
            return;
        }
        _appForeground = NO;
        if (!_isPaused && _videoRecording)
            [self onBtnRecordStartClicked];
       
    }else{
        AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
        if (options == AVAudioSessionInterruptionOptionShouldResume) {
            _appForeground = YES;
        }
    }
}

- (void)onAppDidEnterBackGround:(UIApplication*)app
{
    _appForeground = NO;
    if (!_isPaused && _videoRecording)
        [self onBtnRecordStartClicked];

}

- (void)onAppWillEnterForeground:(UIApplication*)app
{
    _appForeground = YES;

}

- (void)onAppDidBecomeActive:(UIApplication*)app
{
    _appForeground = YES;

}

#pragma mark - Common UI
-(void)initUI
{
    self.title = @"视频录制";
    _videoRecordView = [[UIView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:_videoRecordView];
    
//    UIImageView* mask_top = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, BUTTON_CONTROL_SIZE)];
//    [mask_top setImage:[UIImage imageNamed:@"video_record_mask_top"]];
//    [self.view addSubview:mask_top];
    
    UIButton * leftBackBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 60, 50)];
    [leftBackBtn setImage:[UIImage imageNamed:@"nav_but_fanhui_default"] forState:UIControlStateNormal];
    [leftBackBtn setTitle:@"返回" forState:UIControlStateNormal];
    [leftBackBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [leftBackBtn addTarget:self action:@selector(leftBackAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftBackBtn];
    
    _nextStepBtn = [[UIButton alloc] initWithFrame:CGRectMake(XQScreenW-70,10,60,50)];
    [_nextStepBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [_nextStepBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [_nextStepBtn addTarget:self action:@selector(nextStepAcion) forControlEvents:UIControlEventTouchUpInside];
    _nextStepBtn.hidden = YES;
    [self.view addSubview:_nextStepBtn];
    
    
    
    UIImageView* mask_buttom = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 100, self.view.frame.size.width, 100)];
    [mask_buttom setImage:[UIImage imageNamed:@"video_record_mask_buttom"]];
    [self.view addSubview:mask_buttom];


    _btnStartRecord = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, BUTTON_RECORD_SIZE, BUTTON_RECORD_SIZE)];
    _btnStartRecord.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height - BUTTON_RECORD_SIZE + 10);
    [_btnStartRecord setImage:[UIImage imageNamed:@"startrecord"] forState:UIControlStateNormal];
    [_btnStartRecord setImage:[UIImage imageNamed:@"startrecord_press"] forState:UIControlStateSelected];
    [_btnStartRecord addTarget:self action:@selector(onBtnRecordStartClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnStartRecord];
    
    
    _btnCamera = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnCamera.bounds = CGRectMake(0, 0, 30, 30);
    _btnCamera.center = CGPointMake( _btnStartRecord.left / 3, _btnStartRecord.center.y);
    [_btnCamera setImage:[UIImage imageNamed:@"cameraex"] forState:UIControlStateNormal];
    [_btnCamera addTarget:self action:@selector(onBtnCameraClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnCamera];
    
    _btnBeauty = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnBeauty.bounds = CGRectMake(0, 0, 30, 30);
    _btnBeauty.center = CGPointMake(_btnStartRecord.left / 4 * 3 , _btnStartRecord.center.y);
    [_btnBeauty setImage:[UIImage imageNamed:@"beautyex"] forState:UIControlStateNormal];
    [_btnBeauty addTarget:self action:@selector(onBtnBeautyClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnBeauty];
    
    _btnDone = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnDone.bounds = CGRectMake(0, 0, 30, 30);
    _btnDone.center = CGPointMake(XQScreenW/4+_btnStartRecord.centerX, _btnStartRecord.center.y);
    [_btnDone setImage:[UIImage imageNamed:@"localVideo"] forState:UIControlStateNormal];
    [_btnDone setTitleColor:UIColor.brownColor forState:UIControlStateNormal];
    [_btnDone addTarget:self action:@selector(onBtnDoneClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnDone];
    
//    _btnLive = [UIButton buttonWithType:UIButtonTypeCustom];
//    _btnLive.bounds = CGRectMake(0, 0, 30, 30);
//    _btnLive.center = CGPointMake(XQScreenW/2+_btnStartRecord.right / 3*2, _btnStartRecord.center.y);
//    [_btnLive setImage:[UIImage imageNamed:@"TXLive"] forState:UIControlStateNormal];
//    [_btnLive addTarget:self action:@selector(onBtnLiveClicked) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:_btnLive];
    
    _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 40, 20)];
    _progressView.center = CGPointMake(self.view.frame.size.width / 2, _btnStartRecord.frame.origin.y - 20);
    _progressView.progressTintColor = RGB_HEX(0X0ACCAC);
    _progressView.tintColor = RGB_HEX(0XBBBBBB);
    _progressView.progress = _currentRecordTime / MAX_RECORD_TIME;
    [self.view addSubview:_progressView];
    
    _minimumView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 3, 6)];
    _minimumView.backgroundColor = RGB_HEX(0X0ACCAC);
    _minimumView.center = CGPointMake(_progressView.frame.origin.x + _progressView.width*MIN_RECORD_TIME/MAX_RECORD_TIME, _progressView.center.y);
    [self.view addSubview:_minimumView];
    
    UILabel * minimumLabel = [[UILabel alloc]init];
    minimumLabel.frame = CGRectMake(5, 1, 150, 150);
    [minimumLabel setText:@"至少要录到这里"];
    [minimumLabel setFont:[UIFont fontWithName:@"" size:14]];
    [minimumLabel setTextColor:[UIColor whiteColor]];
    [minimumLabel sizeToFit];
    UIImageView * minumumImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, minimumLabel.frame.size.width + 10, minimumLabel.frame.size.height + 5)];
    minumumImageView.image = [UIImage imageNamed:@"bubble"];
    [minumumImageView addSubview:minimumLabel];
    minumumImageView.center = CGPointMake(_minimumView.center.x + 13, _minimumView.frame.origin.y - minimumLabel.frame.size.height);
    [self.view addSubview:minumumImageView];
    minumumImageView.hidden = YES;
    minimumLabel.hidden = YES;
    
    _recordTimeLabel = [[UILabel alloc]init];
    _recordTimeLabel.frame = CGRectMake(0, 0, 100, 100);
    [_recordTimeLabel setText:@"00:00"];
    _recordTimeLabel.font = [UIFont systemFontOfSize:10];
    _recordTimeLabel.textColor = [UIColor whiteColor];
    _recordTimeLabel.textAlignment = NSTextAlignmentLeft;
    [_recordTimeLabel sizeToFit];
    _recordTimeLabel.center = CGPointMake(CGRectGetMaxX(_progressView.frame) - _recordTimeLabel.frame.size.width / 2, _progressView.frame.origin.y - _recordTimeLabel.frame.size.height);
    [self.view addSubview:_recordTimeLabel];
    
}

-(void)leftBackAction
{
    if (!_videoRecording){
        
        [_vBeauty saveValues];
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self pauseVideoRecord];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提醒" message:@"是否停止录制" preferredStyle: UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [_vBeauty saveValues];
            [self stopVideoRecord];
            [self.navigationController popViewControllerAnimated:YES];
          
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self resumeVideoRecord];
            
        }]];
        [self presentViewController:alert animated:true completion:nil];
    }
    
    
}

#pragma mark - NEXTSTEP

-(void)nextStepAcion
{
    BMHLog(@"下一步");
    [_vBeauty saveValues];
    if (!_videoRecording)
        return;
        
    
    [self stopVideoRecord];
    
    
}

#pragma mark - 直播入口（预留方法）

-(void)onBtnLiveClicked
{
    BMHLog(@"短视频入口直播");
    if ([self checkCameraAuthorization]) {
//        WaitReciveViewController *waitcall = [[WaitReciveViewController alloc] init];
//        waitcall.backActionBlock = ^{
//            [self.navigationController popViewControllerAnimated:NO];
//        };
//        [self.navigationController presentViewController:waitcall animated:YES completion:nil];

    }
}

#pragma mark - 本地选择视频

- (void)onBtnDoneClicked
{

    BMHLog(@"本地视频");
    if (!_videoRecording){
        
        QBImagePickerController* imagePicker = [[QBImagePickerController alloc] init];
        imagePicker.mediaType = QBImagePickerMediaTypeVideo;
        imagePicker.delegate = self;
        imagePicker.allowsMultipleSelection = NO;
        imagePicker.showsNumberOfSelectedAssets = NO;
        [self.navigationController pushViewController:imagePicker animated:YES];
        
    }else{
        [self pauseVideoRecord];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提醒" message:@"是否停止录制" preferredStyle: UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            _isLocalVideo = YES;
            [self stopVideoRecord];
            
            QBImagePickerController* imagePicker = [[QBImagePickerController alloc] init];
            imagePicker.mediaType = QBImagePickerMediaTypeVideo;
            imagePicker.delegate = self;
            imagePicker.allowsMultipleSelection = NO;
            imagePicker.showsNumberOfSelectedAssets = NO;
            [self.navigationController pushViewController:imagePicker animated:YES];
            
            
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self resumeVideoRecord];
            
        }]];
        [self presentViewController:alert animated:true completion:nil];
    }
    
    
    
}


#pragma mark - QBImagePickerControllerDelegate
- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets
{
    _assetsAry  = assets;

    PHAsset *expAsset = _assetsAry[0];
    [[PHImageManager defaultManager] requestAVAssetForVideo:expAsset options:nil resultHandler:^(AVAsset * _Nullable avAsset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            
            TXVideoInfo * videoMsg = [TXVideoInfoReader getVideoInfoWithAsset:avAsset];
            CGFloat duration = videoMsg.duration;
            BMHLog(@"视频选择时间： %.0f",duration);
            if (duration < 3) {
                
                [HelpTool startTipViewWithText:@"视频时长不能小于3秒" duration:1.0 type:kTipViewTypeNone];
                
            }else{
                
                VideoLoadingController *loadvc = [[VideoLoadingController alloc] init];
                loadvc.composeMode = NO;
                
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loadvc];
                [self presentViewController:nav animated:YES completion:nil];
                [loadvc exportAssetList:assets];
                
            }

            
        });
    }];
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController
{
    NSLog(@"imagePicker Canceled.");
    
    [self.navigationController popViewControllerAnimated:YES];
    
}


-(void)onBtnRecordStartClicked
{
    
    if (!_videoRecording)
    {
        _nextStepBtn.hidden = NO;
        [self startVideoRecord];
    }
    else
    {
        if (_isPaused) {
            [[TXUGCRecord shareInstance] resumeRecord];
            [_btnStartRecord setImage:[UIImage imageNamed:@"stoprecord"] forState:UIControlStateNormal];
            [_btnStartRecord setImage:[UIImage imageNamed:@"stoprecord_press"] forState:UIControlStateSelected];
            _isPaused = NO;
        }
        else {
            [[TXUGCRecord shareInstance] pauseRecord];
            [_btnStartRecord setImage:[UIImage imageNamed:@"startrecord"] forState:UIControlStateNormal];
            [_btnStartRecord setImage:[UIImage imageNamed:@"startrecord_press"] forState:UIControlStateSelected];
            _isPaused = YES;
        }
    }
}



-(void)startCameraPreview
{

    if (_cameraPreviewing == NO)
    {
        //简单设置
        //        TXUGCSimpleConfig * param = [[TXUGCSimpleConfig alloc] init];
        //        param.videoQuality = VIDEO_QUALITY_MEDIUM;
        //        [[TXUGCRecord shareInstance] startCameraSimple:param preview:_videoRecordView];
        //自定义设置
        NSString * VideoLeveStr   = [UserDefaults objectForKey:VideoLeveID];
        TXUGCCustomConfig * param = [[TXUGCCustomConfig alloc] init];
        if (VideoLeveStr.length > 0) {
            if ([VideoLeveStr isEqualToString:@"0"]) {
                param.videoResolution =  VIDEO_RESOLUTION_360_640;
            }else if ([VideoLeveStr isEqualToString:@"1"]){
                param.videoResolution =  VIDEO_RESOLUTION_540_960;
            }else if ([VideoLeveStr isEqualToString:@"2"]){
                param.videoResolution =  VIDEO_RESOLUTION_720_1280;
            }
            
        }else{
            param.videoResolution =  VIDEO_RESOLUTION_540_960;
        }
        
        param.videoFPS = 20;
        param.videoBitratePIN = 1200;
        [[TXUGCRecord shareInstance] startCameraCustom:param preview:_videoRecordView];
        [TXUGCRecord shareInstance].videoProcessDelegate = self;
        
//        UIImage *image = [UIImage imageNamed:@"TXwatermark100"];
//        [[TXUGCRecord shareInstance] setWaterMark:image normalizationFrame:CGRectMake(1-0.30, 0.02, 0.25 , 0.25 * image.size.height / image.size.width)];

        [_vBeauty initValues];

        _cameraPreviewing = YES;
    }

}

/* 各种情况下的横竖屏推流 参数设置
 //activity竖屏模式，竖屏推流
 [[TXUGCRecord shareInstance] setHomeOrientation:VIDEO_HOME_ORIENTATION_DOWN];
 [[TXUGCRecord shareInstance] setRenderRotation:0];
 
 //activity竖屏模式，home在右横屏推流
 [[TXUGCRecord shareInstance] setHomeOrientation:VIDOE_HOME_ORIENTATION_RIGHT];
 [[TXUGCRecord shareInstance] setRenderRotation:90];
 
 //activity竖屏模式，home在左横屏推流
 [[TXUGCRecord shareInstance] setHomeOrientation:VIDEO_HOME_ORIENTATION_LEFT];
 [[TXUGCRecord shareInstance] setRenderRotation:270];
 
 //activity横屏模式，home在右横屏推流 注意：渲染view要跟着activity旋转
 [[TXUGCRecord shareInstance] setHomeOrientation:VIDOE_HOME_ORIENTATION_RIGHT];
 [[TXUGCRecord shareInstance] setRenderRotation:0];
 
 //activity横屏模式，home在左横屏推流 注意：渲染view要跟着activity旋转
 [[TXUGCRecord shareInstance] setHomeOrientation:VIDEO_HOME_ORIENTATION_LEFT];
 [[TXUGCRecord shareInstance] setRenderRotation:0];
 */

- (void)statusBarOrientationChanged:(NSNotification *)note  {
    switch ([[UIDevice currentDevice] orientation]) {
        case UIDeviceOrientationPortrait:        //activity竖屏模式，竖屏录制
        {
            if (_deviceOrientation != UIDeviceOrientationPortrait) {
                
                [[TXUGCRecord shareInstance] setHomeOrientation:VIDEO_HOME_ORIENTATION_DOWN];
                [[TXUGCRecord shareInstance] setRenderRotation:0];
            }
        }
            break;
        case UIDeviceOrientationLandscapeLeft:   //activity横屏模式，home在右横屏录制 注意：渲染view要跟着activity旋转
        {
            if (_deviceOrientation != UIDeviceOrientationLandscapeLeft) {
                [[TXUGCRecord shareInstance] setHomeOrientation:VIDOE_HOME_ORIENTATION_RIGHT];
                [[TXUGCRecord shareInstance] setRenderRotation:0];
            }
            
        }
            break;
        case UIDeviceOrientationLandscapeRight:   //activity横屏模式，home在左横屏录制 注意：渲染view要跟着activity旋转
        {
            if (_deviceOrientation != UIDeviceOrientationLandscapeRight) {
                
                [[TXUGCRecord shareInstance] setHomeOrientation:VIDEO_HOME_ORIENTATION_LEFT];
                [[TXUGCRecord shareInstance] setRenderRotation:0];
                //[[TXUGCRecord shareInstance] startRecord];
            }
        }
            break;
        default:
            break;
    }
}

#pragma  mark - 结束画面预览
-(void)stopCameraPreview
{
    if (_cameraPreviewing == YES)
    {
        [[TXUGCRecord shareInstance] stopCameraPreview];
        [TXUGCRecord shareInstance].videoProcessDelegate = nil;
        _cameraPreviewing = NO;
    }
}

#pragma mark - 开始录制短视频
-(void)startVideoRecord
{
    [self refreshRecordTime:0];
    [self startCameraPreview];
    [[TXUGCRecord shareInstance] startRecord];
    
    [_btnStartRecord setImage:[UIImage imageNamed:@"stoprecord"] forState:UIControlStateNormal];
    [_btnStartRecord setImage:[UIImage imageNamed:@"stoprecord_press"] forState:UIControlStateSelected];
    
    _videoRecording = YES;
    _isPaused = NO;
    
}
#pragma mark - 结束录制短视频
-(void)stopVideoRecord
{
    [[TXUGCRecord shareInstance] stopRecord];
    
    [_btnStartRecord setImage:[UIImage imageNamed:@"startrecord"] forState:UIControlStateNormal];
    [_btnStartRecord setImage:[UIImage imageNamed:@"startrecord_press"] forState:UIControlStateSelected];
    
    
    _isPaused = NO;
    _videoRecording = NO;
}

#pragma mark - 暂停录制短视频(注:切后台时需保持后台运行状态)
-(void)pauseVideoRecord
{
    [[TXUGCRecord shareInstance] pauseRecord];
    [_btnStartRecord setImage:[UIImage imageNamed:@"startrecord"] forState:UIControlStateNormal];
    [_btnStartRecord setImage:[UIImage imageNamed:@"startrecord_press"] forState:UIControlStateSelected];
    _isPaused = YES;
}

#pragma mark - 恢复录制短视频
-(void)resumeVideoRecord
{
    [[TXUGCRecord shareInstance] resumeRecord];
    [_btnStartRecord setImage:[UIImage imageNamed:@"stoprecord"] forState:UIControlStateNormal];
    [_btnStartRecord setImage:[UIImage imageNamed:@"stoprecord_press"] forState:UIControlStateSelected];
    _isPaused = NO;
}

#pragma mark - 切换前后摄像头
-(void)onBtnCameraClicked
{
    _cameraFront = !_cameraFront;
    if (_cameraFront)
    {
        [_btnCamera setImage:[UIImage imageNamed:@"cameraex"] forState:UIControlStateNormal];
    }
    else
    {
        [_btnCamera setImage:[UIImage imageNamed:@"cameraex"] forState:UIControlStateNormal];
    }
    
    [[TXUGCRecord shareInstance] switchCamera:_cameraFront];
}

//-(void)onBtnLampClicked
//{
//    _lampOpened = !_lampOpened;
//    
//    BOOL result = [[TXUGCRecord shareInstance] toggleTorch:_lampOpened];
//    if (result == NO)
//    {
//        _lampOpened = !_lampOpened;
//        [self toastTip:@"闪光灯启动失败"];
//    }
//    
//    if (_lampOpened)
//    {
//        [_btnLamp setImage:[UIImage imageNamed:@"lamp_press"] forState:UIControlStateNormal];
//    }
//    else
//    {
//        [_btnLamp setImage:[UIImage imageNamed:@"lamp"] forState:UIControlStateNormal];
//    }
//    
//}
#pragma mark - 设置美颜视图View
-(void)onBtnBeautyClicked
{
//    [[[BMHAPIManager sharedStatManager] gatherActionId:@"313" userId:[UserDefaults objectForKey:BMHUserId] channelId:nil] subscribeNext:^(id x) {
//
//    } error:^(NSError *error) {
//
//    }];
    _bottomViewShow = !_bottomViewShow;
    
    if (_bottomViewShow)
    {
        [_btnBeauty setImage:[UIImage imageNamed:@"beautyex"] forState:UIControlStateNormal];
    }
    else
    {
        [_btnBeauty setImage:[UIImage imageNamed:@"beautyex"] forState:UIControlStateNormal];
    }
    
    _vBeauty.hidden = !_bottomViewShow;
//    [_vBeauty resetValues];
    [self hideBottomView:_bottomViewShow];
}

- (void)hideBottomView:(BOOL)bHide
{
    _btnStartRecord.hidden  = bHide;
    _btnCamera.hidden       = bHide;
    _btnBeauty.hidden       = bHide;
    _btnLamp.hidden         = bHide;
    _btnDone.hidden         = bHide;
    _btnLive.hidden         = bHide;
    _progressView.hidden    = bHide;
    _recordTimeLabel.hidden = bHide;
    _minimumView.hidden     = bHide;
}

- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (_bottomViewShow)
    {
        UITouch *touch = [[event allTouches] anyObject];
        CGPoint _touchPoint = [touch locationInView:self.view];
        if (NO == CGRectContainsPoint(_vBeauty.frame, _touchPoint))
        {
            [self onBtnBeautyClicked];
        }
    }
}

#pragma mark - BeautySettingPanelDelegate
- (void)onSetBeautyStyle:(int)beautyStyle beautyLevel:(float)beautyLevel whitenessLevel:(float)whitenessLevel ruddinessLevel:(float)ruddinessLevel{
    [[TXUGCRecord shareInstance] setBeautyStyle:beautyStyle beautyLevel:beautyLevel whitenessLevel:whitenessLevel ruddinessLevel:ruddinessLevel];
}

- (void)onSetEyeScaleLevel:(float)eyeScaleLevel
{
    [[TXUGCRecord shareInstance] setEyeScaleLevel:eyeScaleLevel];
}

- (void)onSetFaceScaleLevel:(float)faceScaleLevel
{
    [[TXUGCRecord shareInstance] setFaceScaleLevel:faceScaleLevel];
}

- (void)onSetFilter:(UIImage*)filterImage
{
    [[TXUGCRecord shareInstance] setFilter:filterImage];
}

- (void)onSetGreenScreenFile:(NSURL *)file
{
    [[TXUGCRecord shareInstance] setGreenScreenFile:file];
}

- (void)onSelectMotionTmpl:(NSString *)tmplName inDir:(NSString *)tmplDir
{
    [[TXUGCRecord shareInstance] selectMotionTmpl:tmplName inDir:tmplDir];
}

- (void)onSetFaceVLevel:(float)faceVLevel{
    [[TXUGCRecord shareInstance] setFaceVLevel:faceVLevel];
}

- (void)onSetChinLevel:(float)chinLevel{
    [[TXUGCRecord shareInstance] setChinLevel:chinLevel];
}

- (void)onSetNoseSlimLevel:(float)slimLevel{
    [[TXUGCRecord shareInstance] setNoseSlimLevel:slimLevel];
}

- (void)onSetFaceShortLevel:(float)faceShortlevel{
    [[TXUGCRecord shareInstance] setFaceShortLevel:faceShortlevel];
}

- (void)onSetMixLevel:(float)mixLevel{
    [[TXUGCRecord shareInstance] setSpecialRatio:mixLevel / 10.0];
}

#pragma mark ---- Video Beauty UI ----
-(void)initBeautyUI
{
    NSUInteger controlHeight = [BeautySettingPanel getHeight];
    _vBeauty = [[BeautySettingPanel alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - controlHeight, self.view.frame.size.width, controlHeight)];
    _vBeauty.hidden = YES;
    _vBeauty.delegate = self;
    [self.view addSubview:_vBeauty];
}

-(void)refreshRecordTime:(int)second
{
    _currentRecordTime = second;
    
    _progressView.progress = (float)_currentRecordTime / MAX_RECORD_TIME;
    int min = second / 60;
    int sec = second % 60;
    
    [_recordTimeLabel setText:[NSString stringWithFormat:@"%02d:%02d", min, sec]];
    [_recordTimeLabel sizeToFit];
    UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    UINavigationController *nav = [tabVC.viewControllers objectAtIndex:tabVC.viewControllers.count - 1];
    for (UIViewController *vc in nav.viewControllers) {
        if ([vc isKindOfClass:[XLAnchorCommitInforVC class]]) {
            if (_currentRecordTime > 14) {
                [self nextStepAcion];
            }
        }
        
        if ([vc isKindOfClass:[XLVideoSetController class]]) {
            if (_currentRecordTime > 59) {
                [self nextStepAcion];
            }
        }
    }
}

#pragma mark ---- VideoRecordListener ----
-(void) onRecordProgress:(NSInteger)milliSecond;
{
    NSLog(@"progress: %ld", milliSecond);
    if (milliSecond > MAX_RECORD_TIME * 1000)
    {
        [self nextStepAcion];
    }
    else
    {
        [self refreshRecordTime: milliSecond / 1000];
    }
    
    //test
//    if (_currentRecordTime > 10) {
//        [[TXUGCRecord shareInstance] stopRecord];
//    }
}

#pragma  mark - 短视频录制完成
-(void) onRecordComplete:(TXUGCRecordResult*)result;
{
    
    NSLog(@"vide======%@",result.videoPath);
    if (_appForeground)
    {
        if (_currentRecordTime >= MIN_RECORD_TIME)
        {
            if (result.retCode == UGC_RECORD_RESULT_OK) {

                
                if (_isLocalVideo == NO) {
                    VideoEditViewController * editVC = [[VideoEditViewController alloc] init];
                    editVC.videoPath = result.videoPath;
                    editVC.isForShoot = YES;
                    editVC.ComeFromEditVC = _ComeFromEditVC;
                    [self.navigationController pushViewController:editVC animated:YES];
                }
               
                
                
            }
            else {
                [self toastTip:@"录制失败"];
            }
        } else {
            [self toastTip:@"至少要录够10秒"];
        }
    }
    
    
    [self refreshRecordTime:0];
}


#pragma mark - Misc Methods

- (float) heightForString:(UITextView *)textView andWidth:(float)width{
    CGSize sizeToFit = [textView sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    return sizeToFit.height;
}

- (void) toastTip:(NSString*)toastInfo
{
    CGRect frameRC = [[UIScreen mainScreen] bounds];
    frameRC.origin.y = frameRC.size.height - 100;
    frameRC.size.height -= 100;
    __block UITextView * toastView = [[UITextView alloc] init];
    
    toastView.editable = NO;
    toastView.selectable = NO;
    
    frameRC.size.height = [self heightForString:toastView andWidth:frameRC.size.width];
    
    toastView.frame = frameRC;
    
    toastView.text = toastInfo;
    toastView.backgroundColor = [UIColor whiteColor];
    toastView.alpha = 0.5;
    
    [self.view addSubview:toastView];
    
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
    
    dispatch_after(popTime, dispatch_get_main_queue(), ^(){
        [toastView removeFromSuperview];
        toastView = nil;
    });
}

#pragma mark - TXVideoCustomProcessDelegate
- (GLuint)onPreProcessTexture:(GLuint)texture width:(CGFloat)width height:(CGFloat)height
{
    static int i = 0;
    if (i++ % 100 == 0) {
        NSLog(@"onPreProcessTexture width:%f height:%f", width, height);
    }
    
    return texture;
}

- (void)onTextureDestoryed
{
    NSLog(@"onTextureDestoryed");
}

- (void)onDetectFacePoints:(NSArray *)points
{
    static int i = 0;
    if (i++ % 100 == 0) {
        NSLog(@"onDetectFacePoints.count:%lu", points.count);
    }
}
- (BOOL)checkCameraAuthorization {  //检测相机是否可用和有无授权
    BOOL isCameraAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    if (!isCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"当前设备无法使用摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return isCameraAvailable;
    }
    BOOL isAvalible = YES;
    //ios 7.0以上的系统新增加摄像头权限检测
    if (iOS7) {
        //获取对摄像头的访问权限。
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (authStatus) {
            case AVAuthorizationStatusRestricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限。
                break;
            case AVAuthorizationStatusDenied://用户已经明确否认了这一照片数据的应用程序访问.
                isAvalible = NO;
                break;
            case AVAuthorizationStatusAuthorized://用户已授权应用访问照片数据.
                break;
            case AVAuthorizationStatusNotDetermined://用户尚未做出了选择这个应用程序的问候
                isAvalible =[UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
                break;
            default:
                break;
        }
    }
    AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (statusAudio == AVAuthorizationStatusDenied) {
        isAvalible = NO;
    }

    if (!isAvalible) {
        NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
        NSString *appName = [infoDict objectForKey:@"CFBundleDisplayName"];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:F(@"您关闭了%@的相机/麦克风权限，无法进行拍照。可以在手机 > 设置 > 隐私 > 相机和麦克风中开启权限。", appName) preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL];
        [alert addAction:action1];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }];
        [alert addAction:action2];
        
        
        [[UIViewController topViewController] presentViewController:alert animated:YES completion:NULL];
        
    }
    return isAvalible;
}

#pragma mark - 屏幕方向改变
- (BOOL)shouldAutorotate {
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}



@end
